<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/7 0007
 * Time: 上午 9:40
 */
namespace app\api\controller;


use app\admin\model\Advertise;
use app\admin\model\Type;
use app\common\model\Advertiselocal;
use app\common\model\Advertiselocalconnect;
use app\common\model\Advertisestoreconnect;
use app\common\model\Advertiseticketconnect;
use app\common\model\Storesettlerule;
use app\common\model\Userfocus;
use app\common\model\Userinstore;
use think\Db;
use think\Request;

class Home extends Base{
    //首页商圈分类
    public function index(){
        $aa = Storesettlerule::where(true)->find();
        dump($aa);


    }

    /**
     * 商圈分类
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllType(){
        $res = Type::where(true)->order('sorting ASC')->select();
        return show(config('status.SUCCESS_STATUS'),'ok',$res);
    }

    public function getTypeName(Request $request){
        $param = $request->param();
        if(!$param['typeId']){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $Type = Type::get($param['typeId']);
        if($Type){
            return show(config('status.SUCCESS_STATUS'),'ok',$Type);
        }else{
            return show(config('status.ERROR_STATUS'),'没找到数据','没找到数据');
        }
    }

    /**
     * 获取首页广告
     * @return \think\response\Json
     */
    public function getAdvertise(){
        $Advertiselocal = Advertiselocal::where('status',1)->order('advertiseLocalNumb ASC')->select();
        if(!empty($Advertiselocal)){
            $data['sowingad'] = [];
            $data['windowad'] = [];
            foreach ($Advertiselocal as &$v){
                if($v['type'] == 0){
                    array_push($data['sowingad'],$v);
                }elseif ($v['type'] == 1){
                    array_push($data['windowad'],$v);
                }else{

                }
            }
            //首页轮播图广告
            $this->getLaunchAd($data['sowingad']);

            //首页橱窗广告
            $this->getLaunchAd($data['windowad']);
            return show(config('status.SUCCESS_STATUS'),'ok',$data);
        }else{
            return show(config('status.ERROR_STATUS'),'没有广告位',null);
        }

    }



    private function getLaunchAd($adtype){
        $nowdate = date('Y-m-d H:i:s',time());
        if(!empty($adtype)){
            foreach ($adtype as &$v){
                $Advertiselocalconnect = Advertiselocalconnect::where('advertiseLocalId',$v['id'])->select();
                if($Advertiselocalconnect){
                    //有该广告位的广告
                    //再判断该广告位里面的广告是否有正在投放中的
                    $ad = [];
                    foreach ($Advertiselocalconnect as $value){
                        $Advertise = Advertise::where('id',$value['advertiseId'])->find();
                        if($nowdate>=$Advertise['startTime'] && $nowdate<$Advertise['endTime']){
                            if($Advertise->advertiseUrlStatus == 0){
                                $store = Advertisestoreconnect::where('advertiseId',$Advertise['id'])->find();
                                $Advertise['storeId'] = $store->storeId;
                            }elseif ($Advertise->advertiseUrlStatus == 1){
                                $ticket = Advertiseticketconnect::where('advertiseId',$Advertise['id'])->find();
                                $Advertise['ticketId'] = $ticket->ticketId;
                            }
                            $ad['id'] = $Advertise['id'];
                            $ad['advertiseImgUrl'] = $Advertise['advertiseImgUrl'];
                            $ad['advertiseTitle'] = $Advertise['advertiseTitle'];
                            $ad['advertiseUrlStatus'] = $Advertise['advertiseUrlStatus'];
                            if(isset($Advertise['storeId'])){
                                $ad['storeId'] = $Advertise['storeId'];
                            }
                            if(isset($Advertise['ticketId'])){
                                $ad['ticketId'] = $Advertise['ticketId'];
                            }
                        }

                    }
                    if(!empty($ad)){
                        //有正在投放中的广告
                        $v['ad'] = $ad;
                    }
                }else{
                    //该广告位没有广告显示广告位的默认内容
                }
            }
        }else{

        }
    }

    /**
     * 首页推荐店铺
     * @param string $lat
     * @param string $lng
     * @return bool|string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRecommendStore(Request $request){
        $param = $request->param();
        $start = $param['start'];
        $length = $this->pagelength;
        if(empty($param['city'])){
            return show(config('status.ERROR_STATUS'),'城市不能为空','城市不能为空');
        }
        $where = "WHERE status=1 AND city='$param[city]'";
        if(!empty($param['lat']) && !empty($param['lng'])){
            //有经纬度
            $StoreList = Db::query("SELECT id,imgUrl,name,lat,lng,(round(6371393 * 2 * asin(sqrt(pow(sin(((lat * pi()) / 180 - ({$param['lat']} * pi()) / 180) / 2), 2) + cos(({$param['lat']} * pi()) / 180) * cos((lat * pi()) / 180) * pow(sin(((lng * pi()) / 180 - ({$param['lng']} * pi()) / 180) / 2), 2))))) AS distance FROM `store` {$where} ORDER BY distance ASC LIMIT {$start},{$length}");
            $count = count(Db::query("SELECT *,(round(6371393 * 2 * asin(sqrt(pow(sin(((lat * pi()) / 180 - ({$param['lat']} * pi()) / 180) / 2), 2) + cos(({$param['lat']} * pi()) / 180) * cos((lat * pi()) / 180) * pow(sin(((lng * pi()) / 180 - ({$param['lng']} * pi()) / 180) / 2), 2))))) AS distance FROM `store` {$where}"));
        }else{

            $StoreList = Db::query("SELECT id,imgUrl,name FROM `store` {$where} ORDER BY inStoreCount DESC LIMIT {$start},{$length}");
            $count = count(Db::query("SELECT id,imgUrl,name FROM `store` {$where}"));
        }

        if(!empty($StoreList)){
            foreach ($StoreList as &$v){
                $res = self::getinstoreAndcountFocus($v['id']);
                $v['countInStore'] = $res['countInStore'];
                $v['countFocus'] = $res['countFocus'];
                $Ticket = self::getTicket($v['id']);
                if($Ticket){
                    $v['Ticket'] = $Ticket['name'];
                    $v['TicketId'] = $Ticket['id'];
                }else{
                    $v['Ticket'] = '';
                }
            }
            return show_page(config('status.SUCCESS_STATUS'),'ok',$count,$StoreList);
        }else{
            return show(config('status.ERROR_STATUS'),'暂无数据',null);
        }
    }

    public static function getinstoreAndcountFocus($storeId){
        $Userinstore = Userinstore::where('storeId',$storeId)->select();

        $countInStore = 0;
        $countFocus = 0;
        $Userfocus = Userfocus::where('storeId',$storeId)->select();
        if($Userfocus){
            $countFocus = count($Userfocus);
        }
        if($Userinstore){
            foreach ($Userinstore as $item){
                $countInStore += (int)$item['inStoreCount'];
            }
        }
        $data['countInStore'] = $countInStore;
        $data['countFocus'] = $countFocus;
        return $data;
    }

    public static function getTicket($storeId){
       $Ticket = \app\admin\model\Ticket::where(['storeId'=>$storeId,'status'=>5])->find();
       return $Ticket;
    }



    public function hhaa(){
        //return $this->unicodeDecode('\u65b0\u6d6a\u5fae\u535a');
        $a = urldecode('%E9%99%88%E8%BE%89');
        $b = urlencode('陈辉');

        return $b;
    }

//    public function abcd(){
//        $Ticket = \app\admin\model\Ticket::where(true)->select();
//        $Specialofferruleconnect = Specialofferrule::where(true)->select();
//        foreach ($Ticket as $v){
//            foreach ($Specialofferruleconnect as $v1){
//                if($v['specialOfferId'] == $v1['id']){
//                    \app\admin\model\Ticket::where('id',$v['id'])->update(['name'=>$v1['specialOfferName']]);
//                }
//            }
//        }
//    }
//
//    public function abcde(){
//        $Ticket = \app\admin\model\Ticket::where('status',['=',5],['=',4],'OR')->select();
//        $Specialofferruleconnect = Specialofferruleconnect::where(true)->select();
//        foreach ($Ticket as $v){
//            foreach ($Specialofferruleconnect as $v1){
//                if($v['id'] == $v1['ticketId']){
//                    \app\admin\model\Ticket::where('id',$v['id'])->update(['storeId'=>$v1['storeId']]);
//                }
//            }
//        }
//    }
//
//    public function abcdef(){
//        $Distribution = \app\common\model\Distribution::where('money','>',0)->where('id',['<>','46a581f47db19b66c507831e55cc204f'],['<>','c4b867842fcdaee2176c049bc1cb5849'],['<>','bf4ee4093626c63ccb1f89ff2f9dddc6'],['<>','e51a748951ff6334926eb6ac2abfd078'],['<>','1bkpv4KQA4Ebk7syxdWIWC'],['<>','dlr5RbKKkMI8deQQxQ-F8P'],'AND')->select();
//        $Userbuyticket = Userbuyticket::where('status','>',0)->select();
//        foreach ($Distribution as $v){
//            foreach ($Userbuyticket as $value){
//                if($v['memberId'] == $value['userId'] && $v['ticketId'] == $value['ticketId']){
//                    \app\common\model\Distribution::where('id',$v['id'])->update(['orderNo'=>$value['orderNo']]);
//                }
//            }
//        }
//
//    }
//
//    public function abcde(){
//        $Member = \app\common\model\Member::where('name','not like','%\%%')->field('id,name')->select();
//
//        foreach ($Member as $v){
//            $newname = urlencode($v['name']);
//            \app\common\model\Member::where('id',$v['id'])->update(['name'=>$newname]);
//        }
//
//    }
//
//    public function bcdef(){
//        $User = \app\common\model\User::where('userName','not like','%\%%')->field('id,userName')->select();
//        foreach ($User as $v){
//            $newname = urlencode($v['userName']);
//            \app\common\model\User::where('id',$v['id'])->update(['userName'=>$newname]);
//        }
//    }



}